﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace SilverlightPlayground.LightBox.Controls
{
    [TemplatePart(Name=WaitStar.RootElementName, Type=typeof(Grid))]
    public class WaitStar : Control
    {
        private const string RootElementName = "RootElement";
        private Grid RootElement { get; set; }
        private const string WheelElementName = "WheelElement";
        private Shape WheelElement { get; set; }
        private const string WaitAnimationName = "WaitAnimation";
        private Storyboard WaitAnimation { get; set; }
        private bool initialized;

        #region StarBrushProperty

        public static readonly DependencyProperty StarBrushProperty =
            DependencyProperty.Register(
                "StarBrush",
                typeof(Brush),
                typeof(WaitStar),
                null);

        public Brush StarBrush
        {
            get { return (Brush)GetValue(StarBrushProperty); }
            set { SetValue(StarBrushProperty, value); }
        } 

        #endregion

        #region IsWaitingProperty

        public static readonly DependencyProperty IsWaitingProperty =
            DependencyProperty.Register(
                "IsWaiting",
                typeof(bool),
                typeof(WaitStar),
                new PropertyMetadata(false, (s, e) => ((WaitStar)s).UpdateVisualState()));

        public bool IsWaiting
        {
            get { return (bool)GetValue(IsWaitingProperty); }
            set { SetValue(IsWaitingProperty, value); }
        }

        #endregion

        private void UpdateVisualState()
        {
            if (this.initialized)
            {
                if (this.WaitAnimation != null)
                {
                    if (this.IsWaiting)
                        this.WaitAnimation.Begin();
                    else
                        this.WaitAnimation.Stop();
                }

                this.RootElement.Visibility = this.IsWaiting ? Visibility.Visible : Visibility.Collapsed;
            }
        }

        public WaitStar()
        {
            this.DefaultStyleKey = typeof(WaitStar);
            this.initialized = false;
        }

        public override void OnApplyTemplate()
        {
            this.RootElement = (Grid)this.GetTemplateChild(WaitStar.RootElementName);
            this.WheelElement = (Shape)this.GetTemplateChild(WaitStar.WheelElementName);
            this.WaitAnimation = this.RootElement.Resources[WaitStar.WaitAnimationName] as Storyboard;
            this.initialized = true;
            this.UpdateVisualState();
            base.OnApplyTemplate();
        }
    }
}